package ubadb.core.components.bufferManager.bufferPool.replacementStrategies.lru;

import java.util.Collection;

import ubadb.core.common.Page;
import ubadb.core.components.bufferManager.bufferPool.BufferFrame;
import ubadb.core.components.bufferManager.bufferPool.replacementStrategies.PageReplacementStrategy;
import ubadb.core.exceptions.PageReplacementStrategyException;
import java.util.Date;

public class LRUReplacementStrategy implements PageReplacementStrategy
{	
	private static String NAME = "LRU";
	public BufferFrame findVictim(Collection<BufferFrame> bufferFrames) throws PageReplacementStrategyException
	{		
		LRUBufferFrame victim = null;
		Date oldestUseDate = null;
		
		for(BufferFrame bufferFrame : bufferFrames)
		{
			LRUBufferFrame lruBufferFrame = (LRUBufferFrame) bufferFrame; //safe cast as we know all frames are of this type
			if(lruBufferFrame.canBeReplaced() && (oldestUseDate==null || lruBufferFrame.getUseDate().before(oldestUseDate)))				
			{
				victim = lruBufferFrame;
				oldestUseDate = lruBufferFrame.getUseDate();
			}
		}
		
		if(victim == null)
			throw new PageReplacementStrategyException("No page can be removed from pool");
		else
			return victim;
	}
	
	public BufferFrame createNewFrame(Page page) 
	{
		return new LRUBufferFrame(page);		
	}
	
	public String toString() {
		return NAME;
	}
}